import request from '@/utils/request'
import commonMixin from '@/mixins/commonMixin'
import {
    codeToText
} from "element-china-area-data";
import { getClassifyAllList } from '@/api/goods/classify/index'
import { getCategoryAllList } from '@/api/goods/category'
import { getSupplierAllList } from '@/api/goods/supplier/index';
import { getDicts } from '@/api/system/dict/data/index';
import { listUser } from '@/api/system/user';
import { getDeptSelect } from '@/api/system/dept';
import { listArea } from '@/api/goods/area';
export default {
    mixins: [commonMixin],
    data() {
        return {
            dataSource: [],//列表数据
            multiple: false,//是否多选
            loading: false,//加载状态
            showSearch: true,//是否显示查询条件
            queryParams: {//查询条件
                pageNum: 1,
                pageSize: 10
            },
            total: 0,//总数
            selectedRows: [],//选中的行
            categoryList: [],//商品分类列表
            classifyList: [],//供应商或客户分类
            userList: [],//后台用户列表
            supplierList: [],//供应商/客户
            deptList: [],//部门
            areaList: [],//区域
        };
    },
    computed: {
    },
    created() {
        this.getList()
    },
    methods: {
        codeToText(code) {
            if (code && code.length > 0 && code.split(',').length > 1) {
                let arr = code.split(',');
                return arr.map(item => {
                    return codeToText[item];
                }).join('/');
            }
        },
        handleAdd(row) {
            this.$refs.modelForm.add(row);
        },
        handleEdit(row) {
            console.log('this.$refs.modelForm :>> ', this.$refs.modelForm);
            this.$refs.modelForm.edit(row);
        },
        handleView(row) {
            console.log('this.$refs.modelForm :>> ', this.$refs.modelForm);
            this.$refs.modelForm.view(row);
        },
        /**
         * 查询
         */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList()
        },
        /**
         * @重置查询条件
         */
        resetQuery() {
            this.queryParams = {//查询条件
                pageNum: 1,
                pageSize: 10
            },
                this.getList()
        },
        /**
         * @获取列表
         */
        getList() {
            console.log('666',666);
            this.loading = true;
            var params = {
                url: this.urls.list,
                method: 'get',
                params: this.getQueryParams() //查询条件
            }
            console.log('params :>> ', params);
            request(params).then(res => {
                this.loading = false;
                if (res.code == 200) {
                    this.dataSource = res.rows;
                    this.total = res.total;
                    if (typeof (this.listAfter) === "function") {
                        this.listAfter()
                    }
                } else {
                    this.$modal.msgError(res.msg)
                }
            });
        },
        /**
         * @拼装查询条件
         * @returns 
         */
        getQueryParams() {
            return this.queryParams
        },
        handleDelete(ids) {
            this.$modal.confirm('确定删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request({
                    url: this.urls.delete + '/' + ids,
                    method: 'delete'
                }).then(res => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('删除成功')
                        this.getList()
                    } else {
                        this.$modal.msgError(res.msg)
                    }
                });
            }).catch(() => { });
        },
        /**
         * @控制table是否可以选择
         * @param {*} row 
         * @param {*} index 
         * @returns 
         */
        selectHandle(row, index) {
            return true;
        },
        /**
         * 
         */
        handleSelectionChange(val) {
            this.selectedRows = val;
            this.multiple = val.length > 0;
        },
        rowClick(row, column, event) {
            this.$refs.table.toggleRowSelection(row);
        },
        dbclick(row) {
            console.log('row :>> ', row);
            this.$refs.modelForm.edit(row);
        },
        /**
         * @批量删除
         */
        handleBatchDelete() {
            if (this.selectedRows.length == 0) {
                this.$modal.msgError('请选择要删除的数据');
                return;
            }
            var ids = this.selectedRows.map(item => item.id).join(',');
            this.handleDelete(ids);
        },
        /**
         * @获取供应商或客户分类
         */
        getClassifyAllList(type, callback) {
            let params = { classifyType: type }
            getClassifyAllList(params).then(res => {
                console.log('res :>> ', res);
                this.classifyList = res
                // 数组第一个位置添加全部分类
                this.classifyList.unshift({ id: '', supplierClassifyName: '全部' })
                console.log('this. :>> ', this.classifyList);
                callback && callback(res)
            });
        },
        async generatePrintData() {
            // const canPrint = await this.getPrintAuth()
            // if(!canPrint) return;
            const Cols = this.columns.map(v => {
                let item = {
                    name: v.dataIndex,
                    required: false,
                    size: 255,
                    type: "str",
                    // key:v.dataIndex
                }
                return item
            })
            const data = this.dataSource.map(v => {
                let item = {}
                this.columns.forEach(val => {
                    item[val.dataIndex] = v[val.dataIndex]
                })
                return item;
            })
            // 表体数据
            let table = templateData
            table.Tables[0] = {
                Cols: Cols,
                Data: data,
                Name: 'table'
            }

            // 表头数据
            let ColHead = [], dataHead = []

            for (let key in this.model) {
                ColHead.push({
                    name: key,
                    required: false,
                    size: 255,
                    type: "str",
                })
            }
            table.Tables[1] = {
                Cols: ColHead,
                Data: [this.model],
                Name: 'manInfo'
            }
            table.upload_templ_comment = this.title
            table.upload_templ_name = this.title
            table.upload_templ_user = this.model.loginName || this.model.loginName
            table.template = `${fileName[this.billType]}.fr3`

            console.log('table :>> ', table);
            console.log('fileName :>> ', fileName);
            sendMsg(table, undefined, this.getPrintAuth)
        },
        /**
       * @获取所有分类
       */
        getCategoryAllList() {
            getCategoryAllList().then(res => {
                this.categoryList = this.handleTree(res, 'id')
            }).catch(err => {
                console.log(err)
            });

        },

        /**
        * @获取正常分类
        */
        getCommonCategoryAllList() {
            getCategoryAllList().then(res => {
                var arr = res.filter(item => item.classStatus == 1)
                this.categoryList = this.handleTree(arr, 'id')
                console.log('this.categoryList :>> ', this.categoryList);
            }).catch(err => {
                console.log(err)
            });

        },
        
        /**
         * 获取所有客户/供应商 
         * @param {String | Number} type 
         * type 2:供应商 1:客户
         */
        getSupplierAllList(type) {
            let params = {
                type: type
            }
            getSupplierAllList(params).then(res => {
                this.supplierList = res
            }).catch(err => {
                console.log(err)
            });
        },

        /**
         * @获取字典
         */
        async getDicts(dictType) {
            let arr = []
            if (Array.isArray(dictType)) {
                arr = dictType
            } else {
                arr.push(dictType)
            }
            for (var i = 0; i < arr.length; i++) {
                await getDicts(arr[i]).then(res => {
                    if (res.code == 200) {
                        this[arr[i]] = (res.data || []).map(item => {
                            return {
                                label: item.dictLabel,
                                value: item.dictValue
                            }
                        })
                    } else {
                        this.$modal.msgError(res.msg)
                    }
                });
            }
        },
        // 获取后台用户
        listSysUser() {
            listUser().then(res => {
                this.userList = res.rows
            }).catch(err => {
                console.log(err)
            });
        },
        // 获取部门
        listSysDept() {
            getDeptSelect().then(res => {
                this.deptList = res.data
            }).catch(err => {
                console.log(err)
            });
        },
        // 获取区域
        getArea() {
            listArea().then(res => {
                this.areaList = res.rows
            }).catch(err => {
                console.log(err)
            });
        },
        /**
         * @展开/隐藏树形结构
         */
        handleEdge() {
            this.showTree = !this.showTree
            this.$nextTick(() => {
                setTimeout(() => {
                    this.tableHeight = this.$refs.table.$el.scrollHeight
                }, 200)
            })
        },

    },
};